package com.wys.spring.swagger.plugin;

import lombok.extern.slf4j.Slf4j;
import springfox.bean.validators.plugins.Validators;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;

import javax.validation.constraints.NotBlank;
import java.util.Optional;

/**
 * @author XiaoLin
 * @date 2022年02月14日
 * @time 15:15
 */
@Slf4j
public class NotBlankModelPropertyBuilderPlugin implements ModelPropertyBuilderPlugin {
    @Override
    public void apply(ModelPropertyContext modelPropertyContext) {
        Optional<NotBlank> notNull = this.extractAnnotation(modelPropertyContext);
        if (notNull.isPresent()) {
            log.debug("@NotBlank setting required: true");
            modelPropertyContext.getBuilder().required(true);
        }
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return true;
    }

    public Optional<NotBlank> extractAnnotation(ModelPropertyContext context) {
        return Validators.annotationFromBean(context, NotBlank.class);
    }
}
